/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.me.counttimer;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView.*;
import android.app.AlertDialog ;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.android.NumberPicker ;
import android.view.View.OnLongClickListener ;

import com.android.MyDatabase ;
import com.android.NumberPickerDialog;

/**
 *
 * @author ksemuldie
 */
public class EditSessionActivity extends Activity {
  private int id_session = 0 ;
  static final int NUMBER_DIALOG_ID = 0;
  static final int ACTION_DIALOG_ID = 1;
  private int numberRepeat = 1 ;
  private int delete_repeat ;
  
  @Override
  protected void onResume(){
    super.onResume();

    setContentView(R.layout.edit_session);

    Bundle extras = getIntent().getExtras();
    id_session = extras.getInt(MainActivity.VAL_ID_SESSION) ;

    Button AddRepeat = (Button)findViewById(R.id.submit);
    AddRepeat.setOnClickListener(new View.OnClickListener() {
      public void onClick(View view) {
        // Perform action on click
        //setContentView(R.layout.session);
        Intent myIntent = new Intent(view.getContext(), RepeatActivity.class);
        //Intent myIntent = new Intent(this, NewSessionActivity.class);
        myIntent.putExtra("action", "new");
        myIntent.putExtra(MainActivity.VAL_ID_SESSION, id_session);
        startActivity(myIntent);
        //startActivityForResult(myIntent, 0);
      }
    });

    class ShowViewBinder implements SimpleCursorAdapter.ViewBinder {
      private static final int DATA_COLUMN = 1;
      private static final int STATUS_COLUMN = 3;
      boolean retval = false;

      //@Override
      public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
        
          TextView tv = (TextView) view;
          tv.setBackgroundColor(cursor.getInt(4));

          tv.setTextColor(Color.BLACK) ;

          if(columnIndex == 1){
            Log.i("INFO","set test "+tv.getText()+getString(R.string.s_seconds) );
            tv.setText(tv.getText()+getString(R.string.s_seconds));
          }

          return false;
      }
    }

    MyDatabase db=new MyDatabase(getApplicationContext());
    db.open();  //apriamo il db

    Cursor CSession = db.fetchSession(id_session) ;
    //Toast.makeText(getBaseContext(),"Estratte "+CRepeat.getCount(),Toast.LENGTH_SHORT).show();
    startManagingCursor(CSession);
    //First row exist
    if(CSession.moveToFirst()) {
      TextView SessionName = (TextView) findViewById(R.id.session_name);
      SessionName.setText(CSession.getString(1));

      /*TextView RepeatSession = (TextView) findViewById(R.id.repeat_session);
      numberRepeat = CSession.getInt(2) ;
      RepeatSession.setText(""+numberRepeat);*/

      Button ChangeRepeat = (Button)findViewById(R.id.change_repeat) ;
      //ChangeRepeat.setText(CSession.getInt(2)+""+getString(R.string.change)) ;
      ChangeRepeat.setText(String.format(getString(R.string.change), CSession.getInt(2))) ;
      ChangeRepeat.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
          showDialog(NUMBER_DIALOG_ID);
          
        }
      });
    }

    Cursor c=db.fetchRepeat(id_session);
    startManagingCursor(c);

    SimpleCursorAdapter adapter = new SimpleCursorAdapter( //semplice adapter per i cursor
                        this,
                        R.layout.repeats, //il layout di ogni riga
                        c,
                        new String[]{MyDatabase.ProfileMetaData.REPEAT_NAME_KEY,MyDatabase.ProfileMetaData.REPEAT_SECOND_KEY,MyDatabase.ProfileMetaData.REPEAT_COLOR_KEY},//queste colonne
                        new int[]{R.id.repeat_tv , R.id.second_tv});//in queste views

    ListView list1 = (ListView)this.findViewById(R.id.list_repeater);
    list1.setLongClickable(true) ;
    list1.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
      @Override
      public boolean onItemLongClick(AdapterView parent, View view, int position, long id) {
        delete_repeat = (int)id ;

        showDialog(ACTION_DIALOG_ID);

        
        return true ;
      }
    }) ;
/*
    list1.setOnLongClickListener(new AdapterView.OnLongClickListener() {
      @Override
      public boolean onLongClick(View arg0) {
        showDialog(NUMBER_DIALOG_ID);

        return true ;
      }
    });*/

    list1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView parent, View view,int position, long id){
          Intent myIntent = new Intent(view.getContext(), RepeatActivity.class);
          //Intent myIntent = new Intent(this, NewSessionActivity.class);
          myIntent.putExtra("action", "edit");
          myIntent.putExtra(MainActivity.VAL_ID_SESSION, id_session);
          myIntent.putExtra(RepeatActivity.VAL_ID_REPEAT, (int)id);
          startActivity(myIntent);
          /*
          Intent myIntent = new Intent(v.getContext(), EditSessionActivity.class);
          myIntent.putExtra(MainActivity.VAL_ID_SESSION, (int)id);
          startActivity(myIntent);
          Toast.makeText(getBaseContext(),position +" - "+id+" – Item Selezionato!",Toast.LENGTH_SHORT).show();
           * 
           */
        }
    });
    adapter.setViewBinder(new ShowViewBinder());
    list1.setAdapter(adapter);

    db.close();

    Button StartBtn = (Button) findViewById(R.id.start) ;
    StartBtn.setOnClickListener(new View.OnClickListener() {
      public void onClick(View view) {
        Intent myIntent = new Intent(view.getContext(), PlayerSessionActivity.class);
        //Intent myIntent = new Intent(this, NewSessionActivity.class);
        myIntent.putExtra(MainActivity.VAL_ID_SESSION, id_session);
        startActivity(myIntent);
      }
    });
    //Toast.makeText(getBaseContext(),id_session+" – Item Selezionato!",Toast.LENGTH_SHORT).show();
  }

  @Override
  //protected void onStart(Bundle savedInstanceState) {
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.edit_session);

  }

  private NumberPickerDialog.OnNumberSelected mNumberSetListener =
      new NumberPickerDialog.OnNumberSelected() {
        public void numberSelected(int newNumber) {
          MyDatabase db=new MyDatabase(getApplicationContext());
          db.open();  //apriamo il db

          db.updateRepeatSession(id_session, newNumber);

          db.close() ;

          //TextView RepeatSession = (TextView) findViewById(R.id.repeat_session);
          /*TextView RepeatSession = (TextView)findViewById(R.id.repeat_session);
          RepeatSession.setText(""+newNumber);
*/
          Button ChangeRepeat = (Button)findViewById(R.id.change_repeat) ;
          ChangeRepeat.setText(String.format(getString(R.string.change), newNumber)) ;

          numberRepeat = newNumber ;
          //RepeatSession.setText(newNumber);
        }
    };

  @Override
  protected Dialog onCreateDialog(int id) {
      switch (id) {
        case NUMBER_DIALOG_ID:
          return new NumberPickerDialog(this,mNumberSetListener , numberRepeat);
        
        case ACTION_DIALOG_ID :
          AlertDialog.Builder builder = new AlertDialog.Builder(this);
          builder.setMessage(getString(R.string.confirm_delete))
            .setCancelable(false)
            .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int id) {
                MyDatabase db=new MyDatabase(getApplicationContext());
                db.open();  //apriamo il db

                db.deleteRepeat(delete_repeat) ;
                delete_repeat = 0 ;
                db.close() ;

                Intent myIntent = new Intent(getApplicationContext(), EditSessionActivity.class);
                myIntent.putExtra(MainActivity.VAL_ID_SESSION, id_session) ;
                startActivity(myIntent) ;

                Toast.makeText(getBaseContext(),
                  getString(R.string.deleted_repeate),
                  Toast.LENGTH_SHORT).show();
              }
            }).setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {

              public void onClick(DialogInterface dialog, int id) {
                delete_repeat = 0 ;
                dialog.cancel();
              }
            });
          return builder.create();
        
      }
      return null;
  }
}
